// pages/home-page/add-customer/addCustomer.js
const app = getApp()
const {
  baseUrl
} = require('../../../../utils/baseUrl.js');
const { validateAll, validate } = require('../../../../utils/validator.js')
const date = new Date()
const years = []
const months = []
const days = []
const hours = []
const minutes = []
const seconds = []
const todayValue = [
  date.getFullYear() - 2000,
  date.getMonth(),
  date.getDate() - 1,
  date.getHours(),
  date.getMinutes(),
  date.getSeconds(),
];
for (let i = 2000; i <= 2100; i++) {
  years.push(i);
}
for (let i = 1; i <= 12; i++) {
  months.push(i);
}
for (let i = 1; i <= 31; i++) {
  days.push(i);
}
for (let i = 0; i <= 23; i++) {
  hours.push(i);
}
for (let i = 0; i <= 59; i++) {
  minutes.push(i);
}
for (let i = 0; i <= 59; i++) {
  seconds.push(i);
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    years,
    // year: date.getFullYear(),
    months,
    // month: date.getMonth(),
    days,
    // day: date.getDate(),
    hours,
    // hour: date.getHours(),
    minutes,
    // minute: date.getHours(),
    seconds,
    // second: date.getHours(),
    value: todayValue,
    dateInput: "",
    pickerShow: false,
    date: "",
    radioitems: [
      {
        value: "course",
        name: "关联课程",
        checked: true,
      },
      {
        value: "scene",
        name: "关联场景",
      },
    ],
    coachingSessionName: "",
    description: "",
    validityStartTime: "",
    validityEndTime: "",
    coverImg: {},
    detailImg: {}, //详情图
    coachingClassify: "scene", //培训形式
    targetClassify: "",
    contentResIds: "",
    type: "scene",
    coachingTargetUserIds: [],
    coachingTargets: [],
    members: [],
    loading: false,
    operateType: '',
    coachingSessionId: '',
    showText: '',
    showTargets: '',
    rules: {
      coachingSessionName: [
        { required: true, message: '考试主题必填' }
      ],
      description: [
        { required: true, message: '考试简介必填' }
      ],
      detailResourceId: [
        { required: true, message: '详情图必选' }
      ],
      coverResourceId: [
        { required: true, message: '封面图必选' }
      ],
      contentResIds: [
        { required: true, message: '请选择关联场景' }
      ],
      coachingTargets: [
        { required: true, message: '请选择考试对象' }
      ],
      validityStartTime: [
        { required: true, message: '请选择开始时间' }
      ],
      validityEndTime: [
        { required: true, message: '请选择结束时间' }
      ]
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(app.globalData, 'globalData')
    let operateType = app.globalData.operateType || "new";
    operateType === "edit" &&
      wx.setNavigationBarTitle({
        title: "编辑考试",
      });
    app.globalData.coverImg = {};
    app.globalData.detailImg = {};
    app.globalData.contentResIds = [];
    app.globalData.contentCN = "";
    app.globalData.coachingTargetUserIds = [];
    app.globalData.targetClassify = "";
    app.globalData.coachingTargetUserIdsCN = "";
    let coachingSessionId = app.globalData.coachingSessionId || "";
    // || '1849242289428234240'
    this.setData({
      operateType: operateType,
      coachingSessionId: coachingSessionId,
    });
    if (operateType === "edit" && app.globalData.dataUpdata !== "pending") {
      this.getData();
    } else {
      this.getImage('cover')
      this.getImage('detail')
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.trainInfo) {
      let info = app.globalData.trainInfo;
      this.setData({
        ...info,
      });
    }
    let globalData = app.globalData;
    console.log(globalData);
    //是否更新了数据
    if (app.globalData.dataUpdata === "pending") {
      let coverImg = globalData.coverImg;
      let detailImg = globalData.detailImg;
      let contentResIds = globalData.contentResIds
        ? globalData.contentResIds
        : [];
      let contentCN = globalData.contentCN ? globalData.contentCN.join() : "";
      console.log(contentCN);
      let coachingTargetUserIds = globalData.coachingTargetUserIds
        ? globalData.coachingTargetUserIds
        : [];
      let targetClassify = globalData.targetClassify
        ? globalData.targetClassify
        : "";
      let coachingTargetUserIdsCN = globalData.coachingTargetUserIdsCN
        ? globalData.coachingTargetUserIdsCN.join()
        : [];
      this.setData({
        coachingTargets: coachingTargetUserIds,
        contentResIds: contentResIds,
        showText: contentCN,
        targetClassify: targetClassify,
        showTargets: coachingTargetUserIdsCN,
        coachingTargetUserIds: coachingTargetUserIds,
        coverImg,
        detailImg,
      });
      app.globalData.dataUpdata = "resolve";
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    app.globalData.trainInfo = this.data;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},
  getTodayValue() {
    let date = new Date();
    let arry = [
      date.getFullYear() - 2000,
      date.getMonth(),
      date.getDate() - 1,
      date.getHours(),
      date.getMinutes(),
      date.getSeconds(),
    ];
    return arry;
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  // radioChange(e) {
  //   console.log("radio发生change事件，携带value值为：", e.detail.value);
  //   const items = this.data.radioitems;
  //   for (let i = 0, len = items.length; i < len; ++i) {
  //     items[i].checked = items[i].value === e.detail.value;
  //   }
  //   this.setData({
  //     'radioitems': items,
  //     'coachingClassify': e.detail.value,
  //     'type': e.detail.value,
  //     showText: '',
  //     contentResIds: []
  //   })
  // },

  // 关联课程选择
  linkcourse() {
    app.globalData.contentResIds = this.data.contentResIds;
    app.globalData.contentCN = this.data.showText ? this.data.showText.split("，") : [];
    if (this.data.type === "course") {
      console.log(app.globalData);
      wx.navigateTo({
        url: "/myself/pages/train-manage/linkcourse/linkcourse",
      });
    } else {
      wx.navigateTo({
        url: "/myself/pages/train-manage/linkscene/linkscene",
      });
    }
  },
  // 对象选择
  membersel() {
    app.globalData.coachingTargetUserIds = this.data.coachingTargetUserIds;
    app.globalData.targetClassify = this.data.targetClassify;
    wx.navigateTo({
      url: "/myself/pages/train-manage/membersel/membersel",
    });
  },
  getDateValueByTime(time){
    let date = new Date(time);
    return [
      date.getFullYear() - 2000,
      date.getMonth(),
      date.getDate() - 1,
      date.getHours(),
      date.getMinutes(),
      date.getSeconds(),
    ]
  },
  // 日期选择
  bindDateChangeStart: function (e) {
    let value = this.data.validityStartTime ? this.getDateValueByTime(this.data.validityStartTime) : todayValue
    this.setData({
      value:value,
      pickerShow: true,
      dateInput: "start",
    });
  },
  bindDateChangeEnd: function (e) {
    let value = this.data.validityEndTime ? this.getDateValueByTime(this.data.validityEndTime) : todayValue
    this.setData({
      value:value,
      pickerShow: true,
      dateInput: "end",
    });
  },
  pickerCancel() {
    this.setData({
      pickerShow: false,
    });
  },
  bindChange(e) {
    const val = e.detail.value;
    this.setData({
      value: val,
    });
  },
  pickerSubmit() {
    let value = this.data.value;
    let month = `0${months[value[1]]}`.substr(-2, 2);
    let day = `0${days[value[2]]}`.substr(-2, 2);
    let hour = `0${hours[value[3]]}`.substr(-2, 2);
    let minute = `0${minutes[value[4]]}`.substr(-2, 2);
    let second = `0${seconds[value[5]]}`.substr(-2, 2);
    let date = `${years[value[0]]}-${month}-${day} ${hour}:${minute}:${second}`;
    console.log(date);
    if (this.data.dateInput === "start") {
      if(new Date(date).getTime()<= new Date().getTime()){
        wx.showModal({
          content: '开始时间不能小于等于当前时间',
          showCancel:false
        })
        return false
      }
      this.setData({
        validityStartTime: date,
        pickerShow: false,
      });
    } else {
      const _startTime = this.data.validityStartTime
      if(_startTime){
        if(new Date(date).getTime()<= new Date(_startTime).getTime()){
          wx.showModal({
            content: '结束时间不能小于等于开始时间',
            showCancel:false
          })
          return false
        }
      }else{
        if(new Date(date).getTime()<= new Date().getTime()){
          wx.showModal({
            content: '结束时间不能小于等于当前时间',
            showCancel:false
          })
          return false
        }
      }      
      this.setData({
        validityEndTime: date,
        pickerShow: false,
      });
    }
  },
  //提交审核
  submit: function () {
    this.setData({
      loading:true
    })
    let data = this.bodyEnable()
    let flag = true
    this.data.rules.validityEndTime = [
      { required: true, message: '请选择结束时间' },
      { validator: (rule, value, callback) => {
        if (new Date(value) - new Date(data.validityStartTime) < 1 * 60 * 60 * 1000) {
          callback(new Error('活动有效时间不得低于1小时'))
        } else {
          callback()
        }
      } }
    ]
    validateAll(this.data.rules, data, (valid) => {
      if (!valid) {
        flag = false
        this.setData({
          loading:false
        })
      }
    })
    if (flag) {
      if (this.data.operateType === 'edit') {
        this.editSubmit(data)
      } else {
        this.addSubmit(data)
      }
    }
  },
  bodyEnable() {
    let coverResourceId = this.data.coverImg.resourceId || "";
    let detailResourceId = this.data.detailImg.resourceId || "";
    // let coachingArr = this.data.coachingTargetUserIds || []
    // for (let i = 0; i < arr.length; i++) {

    // }
    let data = {
      coachingClassify: this.data.coachingClassify,
      detailResourceId: detailResourceId,
      coverResourceId: coverResourceId,
      coachingSessionName: this.data.coachingSessionName,
      description: this.data.description,
      validityStartTime: `${this.data.validityStartTime}`,
      validityEndTime: `${this.data.validityEndTime}`,
      id: this.data.coachingSessionId,
      contentResIds: this.data.contentResIds || [],
      targetClassify: this.data.targetClassify,
      coachingTargets: this.data.coachingTargets,
      // coachingTargetUserIds: this.data.coachingTargetUserIds || []
    };
    return data;
  },
  dataFormat(value,fmt) {
    let date = new Date(Number(value))
    var o = {
      "M+": date.getMonth() + 1, //月份
      "d+": date.getDate(), //日
      "h+": date.getHours(), //小时
      "m+": date.getMinutes(), //分
      "s+": date.getSeconds(), //秒
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度
      S: date.getMilliseconds(), //毫秒
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    }
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1
            ? o[k]
            : ("00" + o[k]).substr(("" + o[k]).length)
        );
      }
    }
    return fmt;
  },
  //编辑提交
  addSubmit(data) {
    app.api.post({
      url: 'coaching_vx_admin_session_add',
      data,
    }).then(res => {
      this.setData({
        loading:false
      })
      wx.showToast({
        title: '操作成功',
        icon: 'success',
        duration: 1000
      })
      wx.navigateBack()
    }).cathc(()=>{
      this.setData({
        loading:false
      })
    })
  },
  //编辑提交
  editSubmit(data) {
    app.api.post({
      url: 'coaching_vx_admin_session_edit',
      data,
    }).then(res => {
      this.setData({
        loading:false
      })
      wx.showToast({
        title: '操作成功',
        icon: 'success',
        duration: 1000
      })
      wx.navigateBack()
    }).cathc(()=>{
      this.setData({
        loading:false
      })
    })
  },
  async getData() {
    try {
      wx.showLoading({
        title: "获取数据中",
        mask: true,
      });
      await app.api
        .get({
          url: "coaching_vx_admin_session_detail4Edit",
          data: {
            coachingSessionId: this.data.coachingSessionId,
          },
        })
        .then((res) => {
          console.log(res, "res");
          let cover = {
            url: res.coverUrl,
            resourceId: res.coverResourceId,
          };
          let detail = {
            url: res.detailUrl,
            resourceId: res.detailResourceId,
          };
          let radioitems = this.data.radioitems;
          for (let i = 0; i < radioitems.length; i++) {
            if (radioitems[i].value === res.coachingClassify) {
              radioitems[i].checked = true;
            } else {
              radioitems[i].checked = false;
            }
          }
          console.log(cover);
          app.globalData.coverImg = cover;
          app.globalData.detailImg = detail;
          app.globalData.targetClassify = res.targetClassify;
          this.setData({
            radioitems: radioitems,
            targetClassify: res.targetClassify || "",
            coachingSessionName: res.coachingSessionName || "",
            description: res.description || "",
            validityStartTime: res.validityStartTime || "",
            validityEndTime: res.validityEndTime || "",
            coverImg: cover,
            detailImg: detail,
            type: 'scene',
            coachingClassify: 'scene',
            coachingSessionId: res.coachingSessionId
          });
        });
      this.getTargets();
      if (this.data.coachingClassify === "course") {
        this.getCourse();
      } else {
        this.getScenes();
      }
    } catch (error) {
      wx.hideLoading();
    }
    wx.hideLoading();
  },
  //获取关联课程
  getCourse() {
    app.api
      .get({
        url: "coaching_vx_admin_session_courses",
        data: {
          coachingSessionId: this.data.coachingSessionId,
        },
      })
      .then((res) => {
        console.log(res, "course");
        let string = [];
        let contentResIds = [];
        for (let i = 0; i < res.length; i++) {
          string.push(res[i].courseName);
          contentResIds.push(res[i].courseId);
        }
        this.setData({
          showText: string.join(),
          contentResIds: contentResIds,
        });
        app.globalData.contentResIds = contentResIds;
        app.globalData.contentCN = string;
      });
  },
  //获取场景
  getScenes() {
    app.api
      .get({
        url: "coaching_vx_admin_session_scenes",
        data: {
          coachingSessionId: this.data.coachingSessionId,
        },
      })
      .then((res) => {
        console.log(res, "scene");
        let string = [];
        let contentResIds = [];
        for (let i = 0; i < res.length; i++) {
          string.push(res[i].sceneName);
          contentResIds.push(res[i].sceneId);
        }
        this.setData({
          showText: string.join(),
          contentResIds: contentResIds,
        });
        app.globalData.contentResIds = contentResIds;
        app.globalData.contentCN = string;
      });
  },
  //获取培训对象
  getTargets() {
    app.api
      .get({
        url: "coaching_vx_admin_session_targets",
        data: {
          coachingSessionId: this.data.coachingSessionId,
        },
      })
      .then((res) => {
        console.log(res, "getTargets");
        let arr = [];
        let coachingTargets = [];
        if (res.targets && res.targets.length > 0) {
          for (let i = 0; i < res.targets.length; i++) {
            if(!(res.targets[i].nodeData && res.targets[i].nodeData === 'semiTarget')){
              arr.push(res.targets[i].targetName);
              coachingTargets.push({
                targetId: res.targets[i].targetId,
                targetClassify: res.targets[i].targetClassify,
              });
            }else{
              coachingTargets.push({
                nodeData:'semiTarget',
                targetId: res.targets[i].targetId,
                targetClassify: res.targets[i].targetClassify,
              });
            }
          }
          this.setData({
            showTargets: arr.join(),
            coachingTargetUserIds: coachingTargets,
            coachingTargets,
          });
          app.globalData.coachingTargetUserIds = coachingTargets;
          app.globalData.coachingTargetUserIdsCN = arr;
        }
      });
  },

  chooseImg(e) {
    const { type } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/myself/pages/train-manage/choose-img/chooseImg?type=${type}&fileType=picture`,
    });
  },
  getImage (imageClassify) {
    app.api.post({
      url: 'image_query',
      data: {
        pageSize:20,
        currentPage:1
      }
    }).then(res => {
      if (res.length) {
        const img = {
          url: res[0].imageUrl,
          resourceId: res[0].imageResId,
        }
        app.globalData[`${imageClassify}Img`] = img
        this.setData({
          [`${imageClassify}Img`]: img
        })
      }
    })
  }
});
